<?php defined('SYSPATH') or die('No direct script access.');
require_once(APPPATH. 'classes/model/Model_UserLogin.php');
require_once(APPPATH. 'classes/model/Model_UserRelation.php');
require_once(APPPATH. 'classes/helpers/url.php');
require_once(APPPATH. 'facebook/src/facebook.php');
require_once(APPPATH. 'facebook/src/global.php');

class My_Controller extends Controller {
	protected $uid;
	protected $sex;
	protected $partner_uid;
	protected $profile_data;
	protected $friends;
	protected $controller;
	protected $action;
	public function __construct($request, $response) {
		parent::__construct($request, $response);
		Session::instance();
		if($this->request->is_initial()) ob_start("ob_gzhandler");
		$this->controller = $this->request->controller();
		$this->action = $this->request->action();
		$isLogout = Arr::get($_POST, 'logout', '');
		if($isLogout != '') {
			$this->logout();
			$this->request->redirect(My_URL::app_url());
			exit();
		}

		//facebook login
		$facebook = new Facebook(array(
			'appId'  =>  FACEBOOK_APP_ID,
			'secret' => FACEBOOK_SECRET,
		));

		$user = $facebook->getUser();
		$user_profile = null;
		if ($user)
		{
			try
			{
				$user_profile = $facebook->api('/me');
			}
			catch (FacebookApiException $e)
			{
				error_log($e);
				$user = null;
			}
		}

		$um = new Model_UserLogin();
		$this->uid = null;
		$login_status = null;
		$username = Arr::get($_POST, 'username', '');
		$password = Arr::get($_POST, 'password', '');
		//Login through facebook
		if($user)
		{
			$this->logout();
			//It entry doesn't exist... insert new entry
			if($um->getUidByEmail($user_profile['email'], Model_UserLogin::NETWORK_FB) < 1)
			{
				//***TODO*** : Password issue here to be fixed
				$this->uid = $um->createLogin($user_profile['email'], "**", 
					Model_UserLogin::NETWORK_FB, Model_UserLogin::ST_ACTIVATED);
				$user = $um->createFbLogin($user_profile, $this->uid);
			}
			else
			{
				$this->uid = $user_profile['id'];
			}
			if($this->uid != null) $this->setLogin($this->uid);
		}
		else if($username != '' && $password != '') {
			$this->logout();
			$this->uid = $um->getUid($username, $password);
			if($this->uid != null) $this->setLogin($this->uid);
			else {
				$uid_notactivated = $um->getPendingUid($username, $password);
				if($uid_notactivated != null) {
					//registered but not activated
					$login_status = "Your account is not activated, please check your email to activate it.";
				} else {
					$login_status = "Username or password incorrect";
				}
			}
		}
		else {
			$this->uid = $this->isLoggedIn();
		}
		if($this->uid == NULL) {
			//user not logged in
			$allowed_actions = Kohana::config('app_config.noauth_allowed_pages');
			if(isset($allowed_actions[$this->controller]) && 
				array_search($this->action, $allowed_actions, true) !== false) return;
			$view = View::factory('layout_noauth');
			$view->url = $facebook->getLoginUrl(array('scope'=>'email'));
			if($login_status) $view->login_status = $login_status;
			echo $view;
			exit();
		} else {
			//Complete profile is higher priority. Prompt for it if not completed.
			$uf = new Model_UserProfile();
			$this->profile_data = $uf->getUserProfileData($this->uid);
			$this->sex = $this->profile_data['sex'];
			if(empty($this->profile_data['pic_url'])) {
				$isSkip = Arr::get($_GET, 'skip', '');
				if($isSkip != '') {
					Cookie::set('skip', '1');
					exit();
				}
				if(!(Cookie::get('skip') == '1' || $this->controller == 'user')) {
					$view = View::factory('upload_pic');
					$view->skip_url = My_URL::app_url()."?skip=1";
					$this->renderLoggedInUserView($view, "Upload profile pic");
					//exit so that further controller/action not get called
					exit();
				}
			}
			//having partner is 2nd priority
			$ur = new Model_UserRelations();
			$this->partner_uid = $ur->getPartner($this->uid);
			if($this->partner_uid == null) {
				if($this->request->is_ajax()) return;
				$allowed_actions = Kohana::config('app_config.single_allowed_pages');
				if(isset($allowed_actions[$this->controller]) && 
				array_search($this->action, $allowed_actions[$this->controller], true) !== false) return;
				
				$view = View::factory('single');
				$view->invite_url = 'user/invite_couple/';
				$this->renderLoggedInUserView($view, "Get Partner");
				//exit so that further controller/action not get called
				exit();
			}
			$this->friends = $ur->getFriends($this->uid);
			if(!is_array($this->friends)) $this->friends = array();
		}
	}
	private function isLoggedIn() {
		$session = Session::instance();
		$uid = $session->get('uid');
		if($uid == -1) {
			return null;
		}
		return $uid;
	}
	public function renderLoggedInUserView($view, $title = 'Welcome to Couple Book') {
		$layout_view = View::factory('layout_user');
		$layout_view->uid = $this->uid;
		$layout_view->title = $title;
		$layout_view->child_view = $view;
		$ur = new Model_UserRelations();
		$layout_view->friends = $ur->getFriends($this->uid);
		echo $layout_view;
	}
	private function setLogin($uid) {
		$session = Session::instance();
		$session->set('uid', $uid);
	}
	private function logout() {
		$session = Session::instance();
		$session->delete('uid');
		Cookie::delete('skip');
	}
}